import {
  fixedWeeksByDay,
  memberInformation,
  VIPInfo,
  siteFixedReserve,
  paymentConfiguration
} from '../../api/index'
import {
  getYMDHMS
} from '../../utils/util'
Page({

  /* 页面的初始数据 */
  data: {
    id: '',
    nowe: getYMDHMS(new Date()).slice(0, 10),
    date: '',
    list: [],
    hklx: '1',
    show: false,
    pwd: '',
    allPrice: 0,
    idList: [],
    name: wx.getStorageSync('venueName'), //场馆名称
    shtel: '',
    shname: '',
    hytel: '',
    hyname: '',
    hyIdCard: '',
    hyid: '',
    des: '',
    zq: '',
    kssj: '',
    jssj: '',
    checkList: [],
    result: [],
    showCheck: false,
    siteId: [],
    payStatue: '0',
    projectId: '',
    dcxz: ''
  },
  getYx() {
    paymentConfiguration({
      param: {
        type: '15',
        code: 'AGREEMENT_BOOKING_SITE'
      }
    }).then(res => {
      this.setData({
        dcxz: res.recordList[0].value
      })
    })
  },
  bindTimeChange: function (e) {
    let str = e.detail.value
    let ch = "-";
    let val = str.replace(new RegExp(ch, 'g'), "/");
    if (this.data.jssj) {
      let valb = this.data.jssj.replace(new RegExp(ch, 'g'), "/");
      if (new Date(val).getTime() >= new Date(valb).getTime()) {
        return wx.showToast({
          title: '开始日期需要小于结束日期',
          icon: 'none',
          duration: 2000
        })
      }
    }
    let valc = this.data.nowe.replace(new RegExp(ch, 'g'), "/");
    if (new Date(val).getTime() < new Date(valc).getTime()) {
      return wx.showToast({
        title: '预定只能选择今天及之后',
        icon: 'none',
        duration: 2000
      })
    }
    this.setData({
      kssj: e.detail.value
    })
  },
  bindTimeChangeb: function (e) {
    let str = e.detail.value
    if (this.data.kssj) {
      let ch = "-";
      let val = str.replace(new RegExp(ch, 'g'), "/");
      let valb = this.data.kssj.replace(new RegExp(ch, 'g'), "/");
      if (new Date(val).getTime() <= new Date(valb).getTime()) {
        return wx.showToast({
          title: '开始日期需要小于结束日期',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      jssj: e.detail.value
    })
  },

  // 关闭密码输入弹框
  onClose() {
    this.setData({
      show: false,
      pwd: ''
    });
  },
  onCloses() {
    this.setData({
      showCheck: false
    });
  },
  // 实时获取密码输入框值
  bindKeyInput(e) {
    this.setData({
      pwd: e.detail.value
    })
  },

  // 获取日期
  getDate() {
    let date = new Date();
    let nnn = date.getFullYear()
    let yyy = date.getMonth() + 1
    let rrr = date.getDate()
    let xq = date.getDay()
    let data = ''
    switch (xq) {
      case 1:
        data = '周一'
        break;
      case 2:
        data = '周二'
        break;
      case 3:
        data = '周三'
        break;
      case 4:
        data = '周四'
        break;
      case 5:
        data = '周五'
        break;
      case 6:
        data = '周六'
        break;
      case 0:
        data = '周日'
        break;
    }
    let res = nnn + '年' + yyy + '月' + rrr + '日' + ' ' + data
    this.setData({
      date: res
    })
  },

  // 查询会员信息
  memberInformation() {
    memberInformation({
      param: {
        userId: wx.getStorageSync('userId')
      }
    }).then(res => {
      if (res.errorCode != '000000') return
      this.setData({
        price: res.record.money
      })
    })
  },


  // 会员提交订单
  memberTJ() {
    var that = this
    if (!that.data.pwd) return wx.showToast({
      title: '请输入支付密码',
      icon: 'none',
      duration: 2000
    })
    payment({
      userId: wx.getStorageSync('userId'),
      param: {
        memberId: wx.getStorageSync('userId'),
        orderId: that.data.ddId,
        payMethod: that.data.type,
        payPwd: that.data.pwd,
        couponsId: that.data.yhqId
      }
    }).then(res => {
      if (res.errorCode == '000000') {
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000,
          mask: true,
          success(res) {
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/paymentSuccessful/index'
              })
            }, 2000)
          }
        })
      } else if (res.errorCode == '70012') {
        wx.showToast({
          title: res.errorMsg,
          icon: 'none',
          duration: 2000,
          success(res) {
            that.setData({
              pwd: ''
            })
          }
        })
      } else if (res.errorCode == '00027') {
        wx.showToast({
          title: res.errorMsg,
          icon: 'none',
          duration: 2000,
          success(res) {
            that.setData({
              pwd: '',
              show: false
            })
          }
        })
      } else {
        wx.showToast({
          title: res.errorMsg,
          icon: 'none',
          duration: 2000,
          success(res) {
            setTimeout(() => {
              wx.reLaunch({
                url: `/pages/paymentFailure/index?ddid=${that.data.ddId}&type=会员支付`
              })
            }, 2000)
          }
        })
      }
    })
  },

  // 提交订单
  submit() {
    if (!this.data.hyid) return wx.showToast({
      title: '请选择会员',
      icon: 'none',
      duration: 2000
    })
    if (!this.data.kssj) return wx.showToast({
      title: '请选择开始时间',
      icon: 'none',
      duration: 2000
    })
    if (!this.data.jssj) return wx.showToast({
      title: '请选择结束时间',
      icon: 'none',
      duration: 2000
    })
    if (this.data.result.length == 0) return wx.showToast({
      title: '请选择固定周期',
      icon: 'none',
      duration: 2000
    })
    let list = [...this.data.list]
    let weeks = [...this.data.result]
    let siteDatas = []
    list.forEach((s) => {
      weeks.forEach((c) => {
        siteDatas.push({
          time: s.begintime + '-' + s.endtime,
          siteId: s.sitemodelid,
          week: c
        })
      })
    })
    siteFixedReserve({
      param: {
        endDay: this.data.jssj,
        memberId: this.data.hyid,
        projectId: this.data.projectId,
        payStatue: this.data.payStatue,
        remarks: this.data.des,
        siteDatas,
        // siteIds: this.data.siteId,
        startDay: this.data.kssj,
        // weeks: this.data.result
      }
    }).then(res => {
      if (res.errorCode == '000000') {
        wx.showToast({
          title: '固定预定成功',
          icon: 'success',
          duration: 2000,
          mask: true,
          success(res) {
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 2000)
          }
        })
      }
    })
  },
  hyClick() {
    if (!this.data.hytel) return wx.showToast({
      title: '请输入手机号',
      icon: 'none',
      duration: 2000
    })
    VIPInfo({
      param: {
        phoneOrNo: this.data.hytel
      }
    }).then(res => {
      if (res.errorCode === '000000') {
        this.setData({
          hyname: res.record.nickName,
          hyIdCard: res.record.number,
          hyid: res.record.id
        });
      }
    }).catch(err => {
      console.log(err)
    })
  },
  hyzqClick() {
    if (!this.data.kssj) return wx.showToast({
      title: '请选择开始时间',
      icon: 'none',
      duration: 2000
    })
    if (!this.data.jssj) return wx.showToast({
      title: '请选择结束时间',
      icon: 'none',
      duration: 2000
    })
    fixedWeeksByDay({
      param: {
        endDay: this.data.jssj,
        siteIds: this.data.siteId,
        startDay: this.data.kssj,
      }
    }).then(res => {
      if (res.errorCode === '000000') {
        this.setData({
          checkList: res.recordList,
          result: [],
          zq: ''
        })
      }
    }).catch(err => {
      console.log(err)
    })
    this.setData({
      showCheck: true
    })
  },
  zqBtn() {
    let result = this.data.result
    let checkList = this.data.checkList
    let arr = []
    for (var i = 0; i < checkList.length; i++) {
      for (var s = 0; s < result.length; s++) {
        if (checkList[i].weekDay == result[s]) {
          arr.push(checkList[i].weekDayName)
        }
      }
    }
    this.setData({
      showCheck: false,
      zq: arr.join(',')
    })
  },
  onChange(e) {
    this.setData({
      payStatue: e.detail
    });
  },
  cancleDate(event) {
    this.setData({
      showDate: false
    });
  },
  onChanges(event) {
    this.setData({
      result: event.detail,
    });
  },

  toggle(event) {
    const {
      index
    } = event.currentTarget.dataset;
    const checkbox = this.selectComponent(`.checkboxes-${index}`);
    checkbox.toggle();
  },

  /* 生命周期函数--监听页面加载 */
  onLoad: function (options) {
    if (options.list) {
      this.setData({
        projectId: options.xmid,
        list: JSON.parse(options.list),
        siteId: JSON.parse(options.siteId)
      })
    }
    this.memberInformation()
    this.getDate()
    this.getYx()
  },

  /* 生命周期函数--监听页面初次渲染完成 */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      name: wx.getStorageSync('venueName')
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})